// Author	: damphat@gmail.com
// Created	: 01/12/2008

#pragma once
#include "vn/NetCommon.h"
#include "vn/Socket.h"
#include "vn/TcpClient.h"


NET_BEGIN

class TcpListener {
public:
	TcpListener() { }
	TcpListener(int port) {
		CHECK_ARG_RANGE_PORT(port);
		m_IPEndPoint = IPEndPoint(IPAddress::Any, port);
	}

	TcpListener(const IPEndPoint &ep) {
		m_IPEndPoint = ep;
	}

	TcpListener(const IPAddress &ip, int port){
		CHECK_ARG_RANGE_PORT(port);
		m_IPEndPoint = IPEndPoint(ip, port);
	}

	void Start(int backlog = SOMAXCONN) {
		if(m_ServerSock.m_Status == StatusClose) {
			try {
				m_ServerSock.OpenTcp();
				m_ServerSock.Bind(m_IPEndPoint);
				m_ServerSock.Listen(backlog);
			}
			catch(SocketException& e) {
				m_ServerSock.Close();
				throw e;
			}
		}
	}

	void AcceptSocket(Socket &out) {
		CHECK_ARG(out.GetStatus() == StatusClose);
		CHECK_STATUS(m_ServerSock.GetStatus() == StatusListening);
		m_ServerSock.Accept(out);
	}

	void AcceptTcpClient(TcpClient &out) {
		CHECK_ARG(out.GetStatus() == StatusClose);
		CHECK_STATUS(m_ServerSock.GetStatus() == StatusListening);
		m_ServerSock.Accept(out.m_Client);
	}

	virtual ~TcpListener() {
	}

public:
	IPEndPoint	m_IPEndPoint;
	Socket		m_ServerSock;
};

NET_END

// current:
// can restart


// Khi lam coding co the gap kho khan/be tac, nen tranh nhung gi?
// khong co duong lui`, mot operation nen thanh cong / that bai, neu that bai nen bao toan trang thai cua object.


// When coding, what difficutus we can face?
//

// Psychology
//
